﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Configuration;
using System.Reflection;

namespace XmlServer.Hosting.Service.Helpers
{
    public class Common
    {

        public static string ServiceName
        {
            get 
            {
                string defaultName = "XmlServer Service";
                try
                {
                    var overrideName = GetAppSettingProjectInstaller("ServiceName");
                    if (!String.IsNullOrEmpty(overrideName)) defaultName = overrideName;
                }
                catch { }
                
                return defaultName; 
            }
        }

        public static string Description
        {
            get 
            { 
                string defaultDescription = "This service starts the XmlServer and starts the listener.  All XmlServer configurations are found in the config file.";

                try
                {
                    var overrideDescription = GetAppSettingProjectInstaller("ServiceDescription");
                    if (!String.IsNullOrEmpty(overrideDescription)) defaultDescription = overrideDescription;
                }
                catch { }                

                return defaultDescription; 
            }
        }

        public static void LogEvent(string source, string log, string msg, EventLogEntryType eventType)
        {
            if (!EventLog.SourceExists(source)) EventLog.CreateEventSource(source, log);
            EventLog.WriteEntry(source, msg, eventType);
            
        }

        public static T GetAppSetting<T>(string Key)
        {
            if (String.IsNullOrEmpty(Key)) return default(T);

            var value = ConfigurationManager.AppSettings[Key];

            T castedValue = (T)Convert.ChangeType(value, typeof(T));

            return castedValue;

        }


        /// <summary>
        /// Called from project installer
        /// </summary>
        public static string GetAppSettingProjectInstaller(string Key)
        {
            string result = "";

            try
            {
                var config = System.Configuration.ConfigurationManager.OpenExeConfiguration(Assembly.GetAssembly(typeof(ProjectInstaller)).Location);
                if (config != null)
                {
                    result = config.AppSettings.Settings[Key].Value;
                }
            }
            catch { }

            return result;
        }
        

    }
}
